<template>
	<div ref="VRRef"></div>
</template>

<script setup>
	import * as THREE from 'three';
import { onBeforeUnmount, onMounted, ref } from 'vue';
	const VRRef = ref(null)
	
	let camera
	const initThree = () => {
		// 创建场景
		const scene = new THREE.Scene()
		// 创建相机
		camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000 );
		// camera.position.set(0, 0, 100)
		// 创建渲染器
		const renderer = new THREE.WebGLRenderer()
		renderer.setSize(window.innerWidth, window.innerHeight)
		// 把生成的渲染器DOM添加到容器中
		VRRef.value.appendChild(renderer.domElement)
		// 创建球体
		const geometry = new THREE.SphereGeometry(15, 64, 32)
		// 创建加载器加载图片
		const loader = new THREE.TextureLoader()
		loader.load('/static/tick2.jpg', texture => {
			// 生成材质
			const material = new THREE.MeshBasicMaterial({
				map: texture,
				side: THREE.DoubleSide
			})
			// 把材质和球体合并
			const mesh = new THREE.Mesh(geometry, material)
			// 添加到场景
			scene.add(mesh)
			
			animate()
		})
		// 渲染场景和相机
		function animate() {
			requestAnimationFrame(animate)
			renderer.render(scene, camera)
		}
		
	}
	
	
	onMounted(() => {
		initThree()
		VRRef.value.addEventListener('touchstart', handleStart)
		VRRef.value.addEventListener('touchmove', handleMove)
	})
	let startX,startY
	const handleStart = e => {
		startX = e.touches[0].clientX
		startY = e.touches[0].clientY
	}
	const handleMove = e => {
		const curX = e.touches[0].clientX;
		const curY = e.touches[0].clientY;
		
		const moveX = curX - startX
		const moveY = curY - startY
		
		const YRotate = moveX * 10 / window.innerWidth
		const XRotate = moveY * 10 / window.innerHeight
		
		camera.rotateY(YRotate)
		camera.rotateX(XRotate)
		startX = curX
		startY = curY
	}
	onBeforeUnmount(() => {
		VRRef.value.removeEventListener('touchstart', handleStart)
		VRRef.value.removeEventListener('touchmove', handleMove)
	})
	
</script>

<style>
	       
</style>
